package gateway.config.security.auth;

import cn.hutool.core.exceptions.ExceptionUtil;
import common.config.http.HttpStatusEnum;
import common.model.response.base.Result;
import common.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理未登录或token过期，返回401状态码，要求重新登录
 *
 * @author 米泽鹏
 * @since 2021-08-05 8:36 下午
 */
@Component
@Slf4j
public class CustomAuthenticationExceptionHandler implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
		log.error(e == null ? "未登录或token过期" : ExceptionUtil.getRootCauseMessage(e));
		ResponseUtil.out(response, Result.error(HttpStatusEnum.UNAUTHORIZED.getCode(), e == null ? "未登录或token过期" : ExceptionUtil.getSimpleMessage(e)));
	}

}
